package org.yanghaokun.org.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.yanghaokun.basic.service.impl.BaseServiceImpl;
import org.yanghaokun.basic.util.PageList;
import org.yanghaokun.org.domain.Department;
import org.yanghaokun.org.mapper.DepartmentMapper;
import org.yanghaokun.org.query.DepartmentQuery;
import org.yanghaokun.org.service.IDepartmentService;

import java.util.List;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public void add(Department department) {
        departmentMapper.save(department);
        //由于后台需要我们需要构造dirPath
        //先判断是否是顶级部门，是就直接追加
        if (department.getParent().getId() == null){
            department.setDirPath("/" + department.getId());
        }else {//不是就获取顶级部门id再追加自己的id就好了
            //找到父部门id
            Long id = department.getParent().getId();
            //根据父部门id找到自己本身
            //通过父本身找到自己的dirPath
            String parentPath = departmentMapper.findOne(id).getDirPath();
            System.out.println(parentPath);
            System.out.println(id);
            department.setDirPath(parentPath + "/" + department.getId());
        }
        departmentMapper.update(department);//再更新一下
    }

    @Override
    public void update(Department department) {
        //由于后台需要我们需要构造dirPath
        //先判断是否是顶级部门，是就直接追加
        // 判断是否是等级部门 追加自己就ok
        if (department.getParent().getId()==null){
            department.setDirPath("/"+department.getId());
        }else{
            // 父亲dirpath+/自己id
            Long parentId = department.getParent().getId();
            String parentDirPath = departmentMapper.findOne(parentId).getDirPath();
            String dirPath = parentDirPath+"/"+department.getId();
            department.setDirPath(dirPath);
        }
        departmentMapper.update(department);
    }

    @Override
    public void bulkDel(List<Long> ids) {
        departmentMapper.bulkDel(ids);
    }

    @Override
    public List<Department> queryDepartTree() {
        return departmentMapper.queryDepartTree();
    }
}
